package com.cavy.platform.server.domain.job;

import com.cavy.platform.server.domain.message.JobMessageSubscribe;
import com.cavy.platform.server.domain.message.StageExecutedSuccessMessage;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.List;

import static com.cavy.platform.server.domain.job.JobStageStatus.EXECUTING;
import static com.cavy.platform.server.domain.job.JobStageStatus.UN_EXECUTED;

@EqualsAndHashCode(callSuper = true)
@Data
public class EndJob extends AbstractJobAction {

    public EndJob() {
    }

    public EndJob(Job job) {
        super(job);
    }

    @JobMessageSubscribe
    public void stageExecutedSuccess(StageExecutedSuccessMessage message) {
        boolean end = true;
        List<JobStage> jobStageList = job.getJobStageList();
        for (JobStage jobStage : jobStageList) {
            if (jobStage.getStatus().equals(UN_EXECUTED) || jobStage.getStatus().equals(EXECUTING)) {
                end = false;
                break;
            }
        }
        if (end) {
            save(this);
            sendJob();
            removeSubscribe();
        }
    }

    @Override
    public void initJobStatus() {
        job.status = JobStatus.FINISH;
    }
}
